#include <stdio.h>

#define READ_BUFFER_SIZE (4 * 1024)

int usage(const char *filename) {
	printf("%s <public key file> <signature file> <zip file> <output file>", filename);

	return 1;
}

int main(int argc, const char *argv[]) {
	if (argc != 5) {
		return usage(argv[0]);
	}
	const char *pub = argv[1];
	const char *sig = argv[2];
	const char *zip = argv[3];
	const char *out = argv[4];

	printf("Packaging %s... ", out);

	FILE *fpub = fopen(pub, "rb");
	if (!fpub) {
		printf("Could not open %s!", pub);
		return -1;
	}
	fseek(fpub, 0, SEEK_END);
	size_t pub_size = ftell(fpub);
	rewind(fpub);

	FILE *fsig = fopen(sig, "rb");
	if (!fsig) {
		printf("Could not open %s!", sig);
		fclose(fpub);
		return -1;
	}
	fseek(fsig, 0, SEEK_END);
	size_t sig_size = ftell(fsig);
	rewind(fsig);

	FILE *fzip = fopen(zip, "rb");
	if (!fzip) {
		printf("Could not open %s!", zip);
		fclose(fpub);
		fclose(fsig);
		return -1;
	}

	FILE *fout = fopen(out, "wb");
	if (!fout) {
		printf("Could not open %s!", out);
		fclose(fpub);
		fclose(fsig);
		fclose(fzip);
		return -1;
	}
	fwrite("Cr24", 4, 1, fout);

	unsigned int version = 2;
	fwrite(&version, 4, 1, fout);

	fwrite(&pub_size, 4, 1, fout);
	fwrite(&sig_size, 4, 1, fout);

	char *buf = new char[READ_BUFFER_SIZE];
	while (!feof(fpub)) {
		size_t n = fread(buf, 1, READ_BUFFER_SIZE, fpub);
		fwrite(buf, 1, n, fout);
	}
	while (!feof(fsig)) {
		size_t n = fread(buf, 1, READ_BUFFER_SIZE, fsig);
		fwrite(buf, 1, n, fout);
	}
	while (!feof(fzip)) {
		size_t n = fread(buf, 1, READ_BUFFER_SIZE, fzip);
		fwrite(buf, 1, n, fout);
	}

	fclose(fout);

	fclose(fpub);
	fclose(fsig);
	fclose(fzip);

	printf("OK\n");

	return 0;
}